package info.nixbear.tgcms.services.dao;

import info.nixbear.tgcms.domain.EntityBase;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.web.bindery.requestfactory.shared.Locator;

public class EntityLocator extends Locator<EntityBase, Long> {

	Logger logger = LoggerFactory.getLogger(EntityLocator.class);
	
	EntityServiceLocator entityServiceLocator = new EntityServiceLocator();
	
	@Override
	public EntityBase create(Class<? extends EntityBase> clazz) {
		try {
			return clazz.newInstance();
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public EntityBase find(Class<? extends EntityBase> clazz, Long id) {
		try {
			return entityServiceLocator.getInstance(clazz).get(id);
		} catch (DaoException e) {
			logger.error("Entity "+clazz+" with id "+id+" not found", e);
			return null;
		}
	}

	@Override
	public Class<EntityBase> getDomainType() {
		throw new UnsupportedOperationException();
	}

	@Override
	public Long getId(EntityBase domainObject) {
		return domainObject.getId();
	}

	@Override
	public Class<Long> getIdType() {
		return Long.class;
	}

	@Override
	public Object getVersion(EntityBase domainObject) {
		return domainObject.getVersion();
	}

}
